<script setup lang="ts">
import { useAccountStore } from '@/stores/account';
import { onMounted,ref} from 'vue';
import { useRoute } from 'vue-router';
import { getInfoApi } from '@/api/path/post';
import { ElMessage } from 'element-plus';
import { obsClient } from '@/utils/obs';
import router from '@/router';


const route = useRoute();
const userId = ref(route.query.userId)

let avatar_id = -1;
const avatar = ref(null); // 声明响应式引用
const info = ref({});
// 获取头像
const isHadAva = ref(false);
const requestAvatar = (id) => {
  const obs = obsClient; 
    obs.listObjects({
      Bucket: 'job-linker',
      Prefix: "personal/avatar/" + id + '/',
    }).then(result => {
      console.log("requestAvatar");
      console.log(result);
      if (result.CommonMsg.Status < 300 && result.InterfaceResult.Contents && result.InterfaceResult.Contents.length > 0) {
        let contents = result.InterfaceResult.Contents
        let element = contents[0]
        let index = 0
        for (index = contents.length - 1; index >= 0; index--) {
          element = contents[index]
          if (element.Key.endsWith('.jpeg') && element.Key.startsWith('personal/avatar/' + id + '/')) {
            break
          }
        }
        if (index<0) {
          return
        }
        avatar_id = index + 1
        let path = element.Key
        console.log("avatar_id",path)
        return obsClient.getObject({
          Bucket: 'job-linker',
          Key: path,
          SaveByType: 'arraybuffer',
        }).then(result => {
          if (result.CommonMsg.Status < 300) {
            const arrayBuffer = result.InterfaceResult.Content;
            const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
            const url = URL.createObjectURL(blob);
            avatar.value = url; // 更新响应式引用
            isHadAva.value = true;
            console.log("=================================",avatar.value)
          } 
        });
      }
    }).catch(error => {
      console.error('请求头像列表时发生错误：', error);
      ElMessage({
      message: '请求头像列表失败。',
      type: 'error',
    });
  });
};
// 获取用户信息
const getUserInfo = async (userId: string) =>{
    getInfoApi(userId).then(res=>{
        if(res.errno === 1){
            info.value =  {
                avatar: avatar.value,
                username : res.userName,
                followingCount: res.count_follows,
                followerCount: res.count_followee,
                postCount: res.count_post,
            }
        }else{
            return {
                avatar:"",
                username : useAccountStore().user.name,
                email: useAccountStore().user.email,
                followingCount: "",
                followerCount: "",
                postCount: "",
            }
        }
    })
}


onMounted(async () => {
    if(userId.value) {
        getUserInfo(userId.value);
        requestAvatar(userId.value)
    }
})
const toThisUser = () => {
    router.push({
    path: "/personalinfo",
      query: {
        userId: route.query.userId,
      }
    });
} 
</script>
<template>
    <div class="info-card" v-if="userId">
        <el-container>
            <el-header class="info">
                <el-avatar v-if="isHadAva" :src="avatar" @click="toThisUser"></el-avatar> <!-- 使用用户首字母作为头像 -->
                <el-avatar v-else @click="toThisUser">{{ String(info.username).charAt(0) }}</el-avatar>
                <div class="info">
                    <h2 class="username">{{ useAccountStore().user.name }}</h2>
                </div>
            </el-header>
            <el-main>
                <el-row :gutter="20" class="counts">
                    <el-col :span="6" class="count-item"> <strong style="font-size: 1.5em">{{ info.followingCount }}</strong><p>关注</p></el-col>
                    <el-col :span="6" class="count-item"> <strong style="font-size: 1.5em">{{ info.followerCount }}</strong><p>粉丝</p></el-col>
                    <el-col :span="6" class="count-item"> <strong style="font-size: 1.5em">{{ info.postCount }}</strong><p>动态</p></el-col>
                </el-row>
            </el-main>
        </el-container>
    </div>
</template>
  
<style scoped>
.info-card {
    display: flex;
    align-items: center;
    max-width: 400px;
    position: relative;
    width: 100%;
    min-width: 200px;
    padding: 20px;
    background-color: white;
    border-radius: 15px;
    border: 2px solid var(--color-plain);
}
  
.avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 16px;
}
  
.info {
    display: flex;
    align-items: center;
    flex: 1;
}
.username {
    margin-left: 10px;
    align-items: center;
    font-size: 1.2em;
}
  
.counts {
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-align: center;
    margin-top: 8px;
    padding-left: 10px;
    padding-right:10px;
    font-size: 1em;
}
  
  .count-item {
    min-width: 50px;
    display: inline-block;
    margin-right: 16px;
  }
  
  .count-item strong {
    font-weight: normal;
    color: #007bff;
  }
  </style>